import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() => LoginState();
}

class LoginState extends State<StatefulWidget> with AutoHideLoading {
  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  GestureRecognizer userAgreementGesture = TapGestureRecognizer()
    ..onTap = () {
      ARouter.instance.pagePush("/web", arguments: {
        "title": appLocal().tipsContentUserAgreement,
        "url": "https://www.ifotocube.com/userterm_en.html"
      });
    };
  GestureRecognizer privacyAgreementGesture = TapGestureRecognizer()
    ..onTap = () {
      ARouter.instance.pagePush("/web", arguments: {
        "title": appLocal().tipsContentPrivacyAgreement,
        "url": "https://www.ifotocube.com/protocol_en.html"
      });
    };

  @override
  void dispose() {
    userAgreementGesture.dispose();
    privacyAgreementGesture.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
        SystemUiOverlayStyle.dark.copyWith(statusBarColor: Colors.transparent));
    return Scaffold(
      body: ChangeNotifierProvider(
        create: (context) => LoginVideModel(),
        child: Container(
          color: const Color(0xffEAECEE),
          child: Stack(
            fit: StackFit.expand,
            children: [
              _topBackgroundWidget(),
              Column(
                children: [
                  _logoWidget(),
                  _subtitleWidget(),
                  Container(
                    margin: const EdgeInsets.only(
                      left: 15,
                      right: 15,
                      top: 29,
                    ),
                    child: TextField(
                      controller: emailController,
                      cursorColor: Color(0xff3F74EF), // 设置光标颜色
                      style: TextStyle(
                          fontWeight: FontWeight.normal, fontSize: 14),
                      decoration: InputDecoration(
                        hintText: AppLocalizationsWrapper.instance
                            .unwrap(context)!
                            .emailAddress,
                        hintStyle: const TextStyle(
                            color: Color(0xff999999), fontSize: 14),
                        fillColor: Colors.white,
                        contentPadding: const EdgeInsets.symmetric(
                            horizontal: 26, vertical: 18),
                        filled: true,
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(28.5),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(
                      left: 15,
                      right: 15,
                      top: 13,
                    ),
                    child: TextField(
                      cursorColor: Color(0xff3F74EF), // 设置光标颜色
                      controller: passwordController,
                      obscureText: true,
                      style: TextStyle(
                          fontWeight: FontWeight.normal, fontSize: 14),
                      decoration: InputDecoration(
                        hintText: AppLocalizationsWrapper.instance
                            .unwrap(context)!
                            .password,
                        hintStyle: const TextStyle(
                            color: Color(0xff999999), fontSize: 14),
                        fillColor: Colors.white,
                        contentPadding: const EdgeInsets.symmetric(
                            horizontal: 26, vertical: 18),
                        filled: true,
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(28.5),
                        ),
                      ),
                    ),
                  ),
                  Builder(builder: (context) {
                    return Container(
                      margin: const EdgeInsets.only(
                        left: 28,
                        right: 17,
                        top: 12,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Opacity(
                            opacity:
                                context.watch<LoginVideModel>().errMsg != null
                                    ? 1
                                    : 0,
                            child: Text(
                              "*${context.read<LoginVideModel>().errMsg}",
                              style: const TextStyle(
                                  color: Color(0xffFF4747), fontSize: 11),
                            ),
                          ),
                          CupertinoButton(
                            padding: EdgeInsets.zero,
                            onPressed: () {
                              ARouter.instance.pagePush("/forgetPassword");
                            },
                            child: Text(
                              "${AppLocalizationsWrapper.instance.unwrap(context)!.forgetPassword}?",
                              style: TextStyle(
                                color: Color(0xff283F4F),
                                fontSize: 11,
                                decoration: TextDecoration.underline,
                                decorationStyle: TextDecorationStyle.solid,
                                decorationThickness: 1,
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  }),
                  Builder(builder: (context) {
                    return CupertinoButton(
                      padding: EdgeInsets.zero,
                      onPressed: () {
                        context.read<LoginVideModel>().login(context,
                            emailController.text, passwordController.text);
                      },
                      child: Container(
                        margin: const EdgeInsets.only(
                          left: 15,
                          right: 15,
                          top: 16,
                        ),
                        height: 57,
                        decoration: BoxDecoration(
                            color: const Color(0xff3F74EF),
                            borderRadius: BorderRadius.circular(28.5)),
                        child: Center(
                            child: Text(
                          AppLocalizationsWrapper.instance
                              .unwrap(context)!
                              .login,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.white,
                              fontWeight: FontWeight.bold),
                        )),
                      ),
                    );
                  }),
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      ARouter.instance.pagePush("/register");
                    },
                    child: Container(
                      margin: const EdgeInsets.only(
                        left: 15,
                        right: 15,
                        top: 13,
                      ),
                      height: 57,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(28.5),
                        border: Border.all(color: Color(0xff999999), width: 1),
                      ),
                      child: Center(
                        child: Text(
                          AppLocalizationsWrapper.instance
                              .unwrap(context)!
                              .register,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.black,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 13),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Consumer<LoginVideModel>(
                        builder: (BuildContext context, value, Widget? child) {
                          return CupertinoButton(
                            padding: EdgeInsets.zero,
                            onPressed: () {
                              value.switchAgreeAgreement();
                            },
                            child: Stack(
                              alignment: AlignmentDirectional.center,
                              children: [
                                Image.asset(
                                  "images/icon_agree_circle.png",
                                  width: 15,
                                  height: 15,
                                ),
                                Opacity(
                                  opacity: value.agreeAgreement ? 1 : 0,
                                  child: Image.asset(
                                    "images/icon_agress_ok.png",
                                    width: 8.5,
                                    height: 6,
                                  ),
                                )
                              ],
                            ),
                          );
                        },
                      ),
                      const SizedBox(width: 10),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 2),
                        child: RichText(
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: AppLocalizationsWrapper.instance
                                    .unwrap(context)!
                                    .readsAndAgrees,
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: 11.0,
                                ),
                              ),
                              TextSpan(
                                recognizer: userAgreementGesture,
                                text: AppLocalizationsWrapper.instance
                                    .unwrap(context)!
                                    .tipsContentUserAgreement,
                                style: TextStyle(
                                  color: Color(0xff3F74EF),
                                  fontSize: 11.0,
                                  decoration: TextDecoration.underline,
                                  decorationColor: Color(0xff3F74EF),
                                  decorationThickness: 2.0,
                                ),
                              ),
                              TextSpan(
                                text:
                                    "${AppLocalizationsWrapper.instance.unwrap(context)!.and}",
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: 11.0,
                                ),
                              ),
                              TextSpan(
                                recognizer: privacyAgreementGesture,
                                text:
                                    "${AppLocalizationsWrapper.instance.unwrap(context)!.tipsContentPrivacyAgreement}",
                                style: TextStyle(
                                  color: Color(0xff3F74EF),
                                  fontSize: 11.0,
                                  decoration: TextDecoration.underline,
                                  decorationColor: Color(0xff3F74EF),
                                  decorationThickness: 2.0,
                                ),
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  _topBackgroundWidget() {
    return Positioned(
      top: -30,
      left: 0,
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.width,
        child: Stack(
          fit: StackFit.expand,
          children: [
            Image.asset(
              "images/bg_login_top.webp",
              fit: BoxFit.cover,
            ),
            Image.asset(
              "images/bg_login_top_mask.png",
              fit: BoxFit.cover,
            )
          ],
        ),
      ),
    );
  }

  _logoWidget() {
    return Padding(
      padding: const EdgeInsets.only(top: 113),
      child: Image.asset(
        "images/icon_login_title.png",
        width: 220,
        height: 66,
        fit: BoxFit.fill,
      ),
    );
  }

  _subtitleWidget() {
    return Padding(
      padding: const EdgeInsets.only(top: 0),
      child: Text(
        "Innovation for Connection",
        style: TextStyle(color: Color(0xff283F4F), fontSize: 15),
      ),
    );
  }
}

class LoginVideModel extends ChangeNotifier {
  String? errMsg;
  bool agreeAgreement = false;

  Future<dynamic> login(
      BuildContext context, String email, String password) async {
    if (email.isEmpty || password.isEmpty) {
      errMsg = AppLocalizationsWrapper.instance
          .unwrap(context)!
          .accountPasswordError;
      notifyListeners();
      return;
    }
    if (!agreeAgreement) {
      FocusManager.instance.primaryFocus?.unfocus();
      bool? res = await _showDialog(context);
      if (res != true) {
        return;
      }
      agreeAgreement = true;
      notifyListeners();
    }

    await EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );

    return HttpManager.instance.doRequest("/user/login",
        parameters: {"email": email, "pwd": password}).then((e) async {
      if (e.isSuccess) {
        await UserManager.instance.login(e.data?['token']);
        await UserManager.instance.syncUserInfo();
        ARouter.instance.pagePushReplacement('/main');
        return true;
      } else {
        Fluttertoast.showToast(msg: e.msg ?? "");
        return true;
      }
    }).catchError((e) {
      Fluttertoast.showToast(
          msg: AppLocalizationsWrapper.instance.unwrap(context).netError);
      return false;
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }

  switchAgreeAgreement() {
    agreeAgreement = !agreeAgreement;
    notifyListeners();
  }

  Future<bool?> _showDialog(BuildContext context) {
    return showCupertinoModalPopup<bool>(
      context: context,
      builder: (BuildContext context) => CupertinoAlertDialog(
        title: Text(AppLocalizationsWrapper.instance.unwrap(context).tips),
        content: RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .tipsContentPre,
                style: TextStyle(
                  color: Color(0xff333333),
                  fontSize: 14.0,
                ),
              ),
              TextSpan(
                text: AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .tipsContentUserAgreement,
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 14.0,
                    fontWeight: FontWeight.bold),
              ),
              TextSpan(
                text: AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .tipsContentAnd,
                style: TextStyle(
                  color: Color(0xff333333),
                  fontSize: 14.0,
                ),
              ),
              TextSpan(
                text: AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .tipsContentPrivacyAgreement,
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 14.0,
                    fontWeight: FontWeight.bold),
              ),
              TextSpan(
                text: AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .tipsContentSuffix,
                style: TextStyle(color: Color(0xff333333), fontSize: 14.0),
              ),
            ],
          ),
        ),
        actions: <CupertinoDialogAction>[
          CupertinoDialogAction(
            isDefaultAction: true,
            onPressed: () {
              Navigator.pop(context, false);
            },
            child: Text(
              AppLocalizationsWrapper.instance.unwrap(context).disagree,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Color(0xff333333),
                fontSize: 14.0,
              ),
            ),
          ),
          CupertinoDialogAction(
            isDestructiveAction: true,
            onPressed: () {
              Navigator.pop(context, true);
            },
            child: Text(
              AppLocalizationsWrapper.instance.unwrap(context).agreeAndContinue,
              style: TextStyle(
                color: Color(0xff3F74EF),
                fontWeight: FontWeight.bold,
                fontSize: 14.0,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
